<?php

class Gallery_Model_UserTags extends Kernel_Model
{

	public function setTags($photo_id, $user_tags_string)
	{
		$this->_clearTags($photo_id);

		if (!empty($user_tags_string)) {
			$user_tags = array_map('trim', explode(',', $user_tags_string));

			// 1. store new tags
			Gallery_Model_Tags::getInstance()->setTags($user_tags);
			

			// 2. bind tags to the photo
			$tags = Gallery_Model_Tags::getInstance()->getTagsByNames($user_tags);
			$this->_bind($photo_id, $tags);
		}
	}

	/**
	 * Bind tags to the photo (exclude duplicates)
	 *
	 * @param integer $photo_id
	 * @param array $tags
	 */
	private function _bind($photo_id, $tags)
	{
		$values = array();
		foreach ($tags as $id => $name) {
			$values[] = array($photo_id, $id);
		}
		
		database::insertValues('photos_2_tags', array('photo_id', 'tag_id'), $values, true);
	}

	private function _clearTags($photo_id)
	{
		database::delete('photos_2_tags', array('photo_id' => (int)$photo_id));
	}


	public function getTags($photo_id)
	{
		$query = '
			SELECT
					`p_t`.`id`,
					`p_t`.`name`
			FROM
					`photos_2_tags` `p_2_t`
			INNER JOIN
					`photo_tags` `p_t`
			ON
					`p_t`.`id` = `p_2_t`.`tag_id`
			WHERE
					`p_2_t`.`photo_id` = ' . (int)$photo_id . '
			ORDER BY
					`p_t`.`name` ASC
		';
		
		return database::fetchPairs($query);
	}

	/**
	 * Return self instance
	 *
	 * @return Gallery_Model_UserTags
	 */
	static public function getInstance()
	{
		return new self;
	}

}